package com.etv.launcher.ui.actvity.desktop;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.etv.launcher.R;
import com.etv.launcher.common.enums.DesktopItemEnum;
import com.etv.launcher.common.utils.ObjectUtil;
import com.etv.launcher.common.utils.UnitUtil;
import com.etv.launcher.databinding.FragmentDesktopBinding;
import com.etv.launcher.model.dto.ApplicationInfoDto;
import com.etv.launcher.model.entity.ApplicationInfoEntity;
import com.etv.launcher.model.pojo.DeskTopAdapterItem;
import com.etv.launcher.model.pojo.TileDrawable;
import com.etv.launcher.ui.actvity.MainActivityViewModel;
import com.etv.launcher.ui.actvity.preference.application.PreferenceApplicationFragment;
import com.etv.launcher.ui.actvity.preference.launcher.PreferenceFragment;
import com.etv.launcher.ui.adapter.DesktopAdapter;
import com.etv.launcher.ui.component.ApplicationIconView;
import com.etv.launcher.ui.component.status.UIBatteryStatusView;
import com.etv.launcher.ui.component.status.UIBluetoothStatusView;
import com.etv.launcher.ui.component.status.DynamicComponentManager;
import com.etv.launcher.ui.component.status.UIPreferenceStatusView;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class DesktopFragment extends Fragment {

    private FragmentDesktopBinding binding;

    private MainActivityViewModel viewModel;

    private TileDrawable tileDrawable;
    private Bitmap cachedBitmap;

    private UIBatteryStatusView battery;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentDesktopBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(requireActivity()).get(MainActivityViewModel.class);
        setTiledBackground(binding.getRoot());
        return binding.getRoot();

    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.addRightComponent();
        this.bindData();

        //设置侧边菜单的大小
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int preferenceWidth = (int) Math.min(screenWidth * 0.3, 700);
        preferenceWidth = Math.max(preferenceWidth, 300);

        // 设置抽屉的布局参数
        DrawerLayout.LayoutParams layoutParams = (DrawerLayout.LayoutParams) binding.preferenceShape.getLayoutParams();
        layoutParams.width = preferenceWidth;
        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.gravity = GravityCompat.END;
        binding.preferenceShape.setLayoutParams(layoutParams);
    }


    private void bindData() {

        viewModel.getAppsLiveData().observe(getViewLifecycleOwner(), new Observer<List<ApplicationInfoEntity>>() {
            @Override
            public void onChanged(List<ApplicationInfoEntity> list) {
                updateApplicationGridUi(list);
            }
        });


        viewModel.getBatteryLiveData().observe(getViewLifecycleOwner(), new Observer<Float>() {
            @Override
            public void onChanged(Float aFloat) {
                battery.setBatteryLevel(aFloat);
            }
        });

    }

    /**
     * 绘制应用表格
     *
     * @param originAppList
     */
    private void updateApplicationGridUi(List<ApplicationInfoEntity> originAppList) {
        List<ApplicationInfoDto> appList = ObjectUtil.copyPropertiesToList(originAppList, ApplicationInfoDto.class);

        List<DeskTopAdapterItem> itemList = new ArrayList<>();
        itemList.add(new DeskTopAdapterItem(DesktopItemEnum.WIDGETS.getValue(), null));

        for (ApplicationInfoDto app : appList) {
            itemList.add(new DeskTopAdapterItem(DesktopItemEnum.APPLICATIONS.getValue(), app));
        }


        //开始计算应用网格细则：列数、组件宽度
        int columnCount = 6;
        int horizontalPadding = 0;
        int itemSpace = UnitUtil.dpToPx(getResources(), 10);
        double viewWidth = UnitUtil.dpToPx(getResources(), ApplicationIconView.getDEFAULT_WIDTH_DP());
        int width = UnitUtil.dpToPx(getResources(), ApplicationIconView.getDEFAULT_WIDTH_DP());
        int screenWidth = getResources().getDisplayMetrics().widthPixels - UnitUtil.dpToPx(getResources(), 40);
        if (screenWidth >= width) {
            width = (int) ((screenWidth - (columnCount - 1) * itemSpace) / (columnCount + 0.28));
            horizontalPadding = (screenWidth - (columnCount * width) - (columnCount - 1) * itemSpace) / 2;
        }

        int viewHeight = (int) ((width / viewWidth) * UnitUtil.dpToPx(getResources(), ApplicationIconView.getDEFAULT_HEIGHT_DP()));
        DesktopAdapter adapter = new DesktopAdapter(binding.desktopRecycler, itemList, columnCount, width, viewHeight,this);
        binding.desktopRecycler.setAdapter(adapter);
        binding.desktopRecycler.setPadding(horizontalPadding, 0, horizontalPadding, 0);

        // 在RecyclerView初始化时添加：
        binding.desktopRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = itemSpace;
            }
        });
    }


    private void setTiledBackground(View view) {
        // 使用协程/线程池进行异步处理（这里使用AsyncTask简化示例）
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... voids) {
                // 1. 优化位图加载
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565; // 减少内存占用
                options.inSampleSize = calculateSampleSize(); // 动态计算缩放比例
                options.inJustDecodeBounds = false;

                try {
                    return BitmapFactory.decodeResource(getResources(), R.drawable.default_back, options);
                } catch (OutOfMemoryError e) {
                    // 内存不足时降级处理
                    options.inSampleSize *= 2;
                    return BitmapFactory.decodeResource(getResources(), R.drawable.default_back, options);
                }
            }

            @SuppressLint("StaticFieldLeak")
            @Override
            protected void onPostExecute(Bitmap bitmap) {
                // 2. 硬件加速优化
                view.setLayerType(View.LAYER_TYPE_HARDWARE, null);

                // 3. 复用已有Drawable
                if (tileDrawable == null) {
                    tileDrawable = new TileDrawable(getResources(), bitmap);
                } else {
                    // 安全回收旧位图
                    if (cachedBitmap != null && !cachedBitmap.isRecycled()) {
                        cachedBitmap.recycle();
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        tileDrawable.setBitmap(bitmap);
                    }
                }

                cachedBitmap = bitmap;

                // 4. 智能背景设置
                if (isAdded() && !isDetached()) {
                    view.post(() -> {
                        view.setBackground(tileDrawable);
                        // 强制刷新显示列表
                        view.getViewTreeObserver().dispatchOnGlobalLayout();
                    });
                }
            }

            private int calculateSampleSize() {
                // 根据屏幕尺寸动态计算最佳采样率
                DisplayMetrics metrics = getResources().getDisplayMetrics();
                int screenWidth = metrics.widthPixels;
                int screenHeight = metrics.heightPixels;

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeResource(getResources(), R.drawable.default_back, options);

                int widthRatio = (int) Math.ceil(options.outWidth / (float) screenWidth);
                int heightRatio = (int) Math.ceil(options.outHeight / (float) screenHeight);

                return Math.max(widthRatio, heightRatio);
            }
        }.execute();
    }

    @Override
    public void onDestroyView() {
        binding = null;

        // 内存回收优化
        if (cachedBitmap != null && !cachedBitmap.isRecycled()) {
            cachedBitmap.recycle();
            cachedBitmap = null;
        }

        if (tileDrawable != null) {
            tileDrawable.setCallback(null);
            tileDrawable = null;
        }

        if (binding != null) {
            binding.getRoot().setBackground(null);
            binding = null;
        }

        super.onDestroyView();
    }

    // 方法参数：容器和已创建的组件（如 ImageView、Button 等）
    private void addRightComponent() {
        DynamicComponentManager manager = new DynamicComponentManager(binding.statusContainer);

        UIBluetoothStatusView bluetooth = new UIBluetoothStatusView(getContext());
        UIPreferenceStatusView preference = new UIPreferenceStatusView(getContext());
        battery = new UIBatteryStatusView(getContext());
        manager.addComponent(preference);
        manager.addComponent(bluetooth);
        manager.addComponent(battery);


        preference.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeFragment(DesktopItemEnum.SYSTEM,null);
            }
        });


    }

    /**
     * @param itemEnum
     * @param application
     */
    public void changeFragment(DesktopItemEnum itemEnum, String application) {
        if (binding.menuDrawer.isDrawerOpen(GravityCompat.END)) {
            binding.menuDrawer.closeDrawer(GravityCompat.END);
        } else {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            if (itemEnum == DesktopItemEnum.SYSTEM) {
                transaction.replace(R.id.preference_container, new PreferenceFragment());
            } else if (itemEnum == DesktopItemEnum.APPLICATIONS) {
                transaction.replace(R.id.preference_container, new PreferenceApplicationFragment(application));
            }

            transaction.commit();
            binding.menuDrawer.openDrawer(GravityCompat.END);
        }
    }

    public boolean onBackPressed() {
        FragmentManager fragmentManager = getChildFragmentManager();
        if (fragmentManager.getBackStackEntryCount() > 0) {
            // 如果侧边栏的Fragment栈不为空，则执行返回逻辑
            fragmentManager.popBackStack();
            return true;  // 已处理返回逻辑
        }

        if (binding.menuDrawer.isDrawerOpen(GravityCompat.END)) {
            binding.menuDrawer.closeDrawer(GravityCompat.END);
            return true;
        }
        return false;  // 未处理返回逻辑
    }

}